package design.graduation.crawler.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import design.graduation.crawler.mapper.CrawlerBookMapper;
import design.graduation.crawler.model.entity.CrawlerBook;
import design.graduation.crawler.service.CrawlerBookService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
/**
 * @author: 洪少尉
 * @Date: 2020/4/20 16:39
 * @Description: 
 */
@Service
public class CrawlerBookServiceImpl extends ServiceImpl<CrawlerBookMapper, CrawlerBook> implements CrawlerBookService{


	@Override
	public void saveAll(List<CrawlerBook> crawlerBooks) {
		QueryWrapper<CrawlerBook> queryWrapper = new QueryWrapper<>();
		for (int i = 0; i < crawlerBooks.size(); i++) {
			queryWrapper = queryWrapper.eq(CrawlerBook.COL_BOOK_NAME, crawlerBooks.get(i).getBookName())
					.eq(CrawlerBook.COL_AUTHOR, crawlerBooks.get(i).getAuthor())
					.or();
		}
		List<CrawlerBook> selectbooks = this.baseMapper.selectList(queryWrapper);
		//等于=0则为不重复
		if (selectbooks.size() == 0) {
			this.saveBatch(crawlerBooks);
		}
		if (selectbooks.size() > 0) {
			List<Integer> num = new ArrayList<>();
			for (int y = 0; y < selectbooks.size(); y++) {
				for (int i = 0; i < crawlerBooks.size(); i++) {
					if (selectbooks.get(0).getBookName().equals(crawlerBooks.get(i).getBookName()) && selectbooks.get(0).getAuthor().equals(crawlerBooks.get(i).getAuthor())) {
						//添加重复的下标
						num.add(i);
					}
				}
			}
			for (int i = 0; i < num.size(); i++) {
				//通过下标移除重复元素
				crawlerBooks.remove((int) num.get(i));
			}
			//保存
			this.saveBatch(crawlerBooks);
		}
	}

	@Override
	public void updateUrl(CrawlerBook crawlerBook) {
		UpdateWrapper<CrawlerBook> updateWrapper = new UpdateWrapper<>();
		updateWrapper.eq(CrawlerBook.COL_BOOK_NAME,crawlerBook.getBookName())
				.eq(CrawlerBook.COL_AUTHOR,crawlerBook.getAuthor())
				.set(CrawlerBook.COL_DOWNLOAD_URL,crawlerBook.getDownloadUrl());
		this.baseMapper.update(crawlerBook,updateWrapper);
	}
}
